package com.example.filelistenerdemo.core;

import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;

/**
 * 自定义文件监听器，继承自FileAlterationListenerAdaptor
 * 用于监听并处理文件系统中的文件和目录变化事件
 */
public class FileListener extends FileAlterationListenerAdaptor {

    // 声明业务服务
    private ListenerService listenerService;

    // 采用构造函数注入服务
    public FileListener(ListenerService listenerService) {
        this.listenerService = listenerService;
    }

    /**
     * 轮询开始事件
     *
     * @param observer The file system observer (ignored)
     */
    @Override
    public void onStart(FileAlterationObserver observer) {
        super.onStart(observer);
    }

    /**
     * 轮询结束事件
     *
     * @param observer The file system observer (ignored)
     */
    @Override
    public void onStop(FileAlterationObserver observer) {
        super.onStop(observer);
    }

    /**
     * 目录创建事件
     *
     * @param directory The directory created (ignored)
     */
    @Override
    public void onDirectoryCreate(File directory) {
        System.out.println("[Created Directory-->"+directory.getAbsolutePath());
    }

    /**
     * 目录修改事件
     *
     * @param directory The directory changed (ignored)
     */
    @Override
    public void onDirectoryChange(File directory) {
        System.out.println("[Changed Directory]-->"+directory.getAbsolutePath());
    }

    /**
     * 目录删除事件
     *
     * @param directory The directory deleted (ignored)
     */
    @Override
    public void onDirectoryDelete(File directory) {
        System.out.println("[Deleted Directory]-->"+directory.getAbsolutePath());
    }

    /**
     * 文件创建事件
     *
     * @param file The file created (ignored)
     */
    @Override
    public void onFileCreate(File file) {
        System.out.println("[Created File]-->"+file.getAbsolutePath());
        // 触发业务
        listenerService.doCreatedFile(file);
    }

    /**
     * 文件修改事件
     *
     * @param file The file changed (ignored)
     */
    @Override
    public void onFileChange(File file) {
        System.out.println("[Amended File]-->"+file.getAbsolutePath());
        // 触发业务
        listenerService.doAmendeFile(file);
    }

    /**
     * 文件删除事件
     *
     * @param file The file deleted (ignored)
     */
    @Override
    public void onFileDelete(File file) {
        System.out.println("[Deleted File]-->"+file.getAbsolutePath());
        // 触发业务
        listenerService.doDeletedFile(file);
    }

}
